package wang.xinqiu.mysqlcontrol.data

import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.sql.Connection
import java.sql.DriverManager
import android.util.Log

class ConnectionPool(private val maxConnections: Int = 3) {
    private val connections = mutableMapOf<String, Connection>()
    private val connectionUsage = mutableMapOf<String, Long>()
    private val mutex = Mutex()
    
    suspend fun getConnection(connectionInfo: ConnectionInfo): Connection? {
        return mutex.withLock {
            val key = "${connectionInfo.host}:${connectionInfo.port}:${connectionInfo.username}"
            
            connections[key]?.let { conn ->
                if (conn.isValid(1)) {
                    connectionUsage[key] = System.currentTimeMillis()
                    Log.d("ConnectionPool", "复用现有连接: $key")
                    return@withLock conn
                } else {
                    Log.d("ConnectionPool", "移除无效连接: $key")
                    connections.remove(key)
                    connectionUsage.remove(key)
                }
            }
            
            // 创建新连接
            if (connections.size >= maxConnections) {
                cleanupOldestConnection()
            }
            
            createNewConnection(connectionInfo)?.also { newConn ->
                connections[key] = newConn
                connectionUsage[key] = System.currentTimeMillis()
                Log.d("ConnectionPool", "创建新连接: $key")
            }
        }
    }
    
    private fun cleanupOldestConnection() {
        val oldestKey = connectionUsage.minByOrNull { it.value }?.key
        oldestKey?.let {
            try {
                connections[it]?.close()
                Log.d("ConnectionPool", "清理最旧连接: $it")
            } catch (e: Exception) {
                Log.e("ConnectionPool", "关闭连接失败", e)
            }
            connections.remove(it)
            connectionUsage.remove(it)
        }
    }
    
    private fun createNewConnection(connectionInfo: ConnectionInfo): Connection? {
        return try {
            Class.forName("com.mysql.jdbc.Driver")
            val url = "jdbc:mysql://${connectionInfo.host}:${connectionInfo.port}/?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
            DriverManager.getConnection(url, connectionInfo.username, connectionInfo.password)
        } catch (e: Exception) {
            Log.e("ConnectionPool", "创建连接失败", e)
            null
        }
    }
    
    suspend fun closeAll() {
        mutex.withLock {
            connections.values.forEach { conn ->
                try {
                    conn.close()
                } catch (e: Exception) {
                    Log.e("ConnectionPool", "关闭连接失败", e)
                }
            }
            connections.clear()
            connectionUsage.clear()
            Log.d("ConnectionPool", "已关闭所有连接")
        }
    }
    
    fun getConnectionCount(): Int = connections.size
}